package com.netty.java.bio;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *  socker 服务端
 */
@Slf4j
public class SocketServer {

    private static final int PORT = 8888;

    public static void main(String[] args){

        ServerSocket server = null;

        try {

            server = new ServerSocket(PORT);

            log.info("Socket Server started");

            log.info(server.getInetAddress().getHostAddress());

            while (true){
                // 接收消息
                Socket accept = server.accept();

                InputStream reader = accept.getInputStream();

                // 保持连接
                InputStreamReader is = new InputStreamReader(reader);

                BufferedReader bufferedReader = new BufferedReader(is);

                String message = bufferedReader.readLine();

                log.info("Socket Server receive message:[{}]", message);

                long currentTime = System.currentTimeMillis();

                log.info("回复消息:[{}]", currentTime);

                // 回复消息
                PrintWriter writer = new PrintWriter(accept.getOutputStream());

                writer.print("CurrentTime is " + currentTime);

                writer.flush();

            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(server != null){
                try {
                    server.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }



    }


}
